"""
课程任务的课时阶段
"""
import json
from django.db import transaction
import logging

from src.utils import record
from common.models import TbCourseTask, TbCoursesTable, TbTeacher

errlog = logging.getLogger("err")


class CourseTaskStage:
    def __init__(self):
        self.ct_table_r = record.CoursesTableRecord()  # 课程时间表
        self.ctr = record.CourseTaskRecord()  # 课程任务

    def get_course_task_current_stage(self, **kwargs):
        """
        获取课程的当前课时时间段
        """
        # 取参
        # --- start ---
        course_task_id = kwargs.get("course_task_id")
        # --- end ---
        time_tables = self.ct_table_r.filter_record(is_delete=0, course_task_id=course_task_id, type=1)
        result = ""
        for time_table in time_tables:
            timetable = eval(time_table.get("timetable"))
            try:
                course_task_index = timetable.index(2)
            except ValueError:
                continue
            class_time = course_task_index
            date = time_table.get("date")
            start_time = class_time
            end_time = class_time + 1
            if start_time < 10:
                start_time = f"0{start_time}"
            if end_time < 10:
                end_time = f"0{end_time}"
            result = f"{date} {start_time}:00-{end_time}:00"
            break
        return result

    def get_stage_index(self, **kwargs):
        """
        获取课时阶段
        """
        # 取参
        # --- start ---
        course_task_id = kwargs.get("course_task_id")
        # --- end ---
        time_tables = self.ct_table_r.filter_record(is_delete=0, course_task_id=course_task_id, type=1)
        result = ""
        result_date = ""
        for time_table in time_tables:
            timetable = eval(time_table.get("timetable"))
            try:
                course_task_index = timetable.index(2)
            except ValueError:
                continue
            date = time_table.get("date")
            result_date = date
            result = course_task_index
            break
        return (result_date, result)

    def finish_stage(self, **kwargs):
        """
        完成课时
        """
        # 取参
        # --- start ---
        course_task_id = kwargs.get("course_task_id")
        # --- end ---
        with transaction.atomic():
            date, stage = self.get_stage_index(course_task_id=course_task_id)
            timetable: TbCoursesTable = self.ct_table_r.get_record_condition(course_task_id=course_task_id, date=date)
            time_table = eval(timetable.timetable)
            time_table[stage] = 1
            timetable.timetable = json.dumps(time_table)
            timetable.save()
            # 检查课时任务是否已经全部完成，如果全部完成了则课程进入下一阶段
            course_task: TbCourseTask = self.ctr.get_record(course_task_id)
            if self.check_course_task_is_finshed(course_task_id=course_task_id):
                course_task.stage = 2
                course_task.save()
            # 师资总课时增加
            teacher: TbTeacher = course_task.teacher
            teacher.total_hours += 1
            teacher.save()
        return self.get_course_table(course_task_id=course_task_id)

    def get_course_table(self, **kwargs):
        """
        获取课程的课程表
        """
        course_task_id = kwargs.get("course_task_id")
        # 查询
        select_info = {
            "course_task_id": course_task_id,
            "is_delete": 0,
        }
        result = []
        time_table = self.ct_table_r.filter_record_order_by_filds("date", **select_info)
        for date_time_table in time_table:
            result.append({
                "date": date_time_table.get("date"),
                "timetable": eval(date_time_table.get("timetable"))
            })
        return result

    def check_course_task_is_finshed(self, **kwargs):
        """
        检查课程任务是否已经全部完成课时
        """
        # 取参
        # --- start ---
        course_task_id = kwargs.get("course_task_id")
        # --- end ---
        result_date, result = self.get_stage_index(course_task_id=course_task_id)
        return result == ""
